import { LoginForm, ProFormCaptcha, ProFormDependency, ProFormText } from "@ant-design/pro-components";
import { useState } from "react";
import { message, Modal, Tabs } from "antd";
import { LockOutlined, PhoneOutlined } from "@ant-design/icons";
import { MOBILE_REGEXP } from "common/utils/regexp";
import { openRegisterModal } from "@/components/RegisterModal";
import { loginVcodeKeyStorage, tokenStorage } from "@/utils/storage";
import { vcodeV1ControllerSendMobileVcode } from "@/services/auto/vcode";
import { SendVcodeType } from "common/utils/data";
import { userV1ControllerLogin } from "@/services/auto/user";
import { useModel } from "@umijs/max";
import Image from "@/components/Image";

interface FormData extends Omit<API.UserLoginDto, 'vcodeKey'> {
}

function Login({onSuccess}: {onSuccess: ()=>void}){
  const [loginType, setLoginType] = useState<LoginType>('mobileVcode');

  const {runAsync} = useModel('user', ({runAsync})=>{
    return {
      runAsync,
    }
  });
  return <LoginForm<FormData>
    logo={<Image src={require('@/assets/imgs/logo_200x.png')} height={44} />}
    title="毁HIFI"
    subTitle="专业耳机数据测评网站"
    onFinish={(values)=>{
      return userV1ControllerLogin({
        mobile: values.mobile,
        password: values.password,
        vcode: values.vcode,
        vcodeKey: loginVcodeKeyStorage.get(values.mobile) ?? undefined,
      }).then((res)=>{
        tokenStorage.set(res.token);
        message.success('登录成功');
        runAsync();
        onSuccess();
        return true;
      }).catch(()=>{
        return false;
      })
    }}
    /*actions={
      <Space>
        其他登录方式
        <AlipayCircleOutlined style={iconStyles} />
        <TaobaoCircleOutlined style={iconStyles} />
        <WeiboCircleOutlined style={iconStyles} />
      </Space>
    }*/
  >
    <div className="text-red-500">由于运营商报备问题，若您的手机为移动号码，存在验证码发送失败的情况，给您带来不便，敬请谅解</div>
    <Tabs
      centered
      activeKey={loginType}
      onChange={(activeKey) => setLoginType(activeKey as LoginType)}
      items={[
        {
          key: 'mobileVcode',
          label: '手机验证码登录'
        },
        {
          key: 'mobilePassword',
          label: '手机密码登录'
        }
      ]}
    />
    <ProFormText
      fieldProps={{
        size: 'large',
        prefix: <PhoneOutlined />,
      }}
      name="mobile"
      placeholder={'手机号'}
      rules={[
        {
          required: true,
          pattern: MOBILE_REGEXP,
          message: '请输入正确格式的手机号',
        },
      ]}
    />
    {loginType === 'mobileVcode' && (
      <>
        <ProFormDependency name={['mobile']}>
          {
            ({mobile})=>{
              return <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  maxLength: 6,
                }}
                captchaProps={{
                  size: 'large',
                }}
                placeholder={'6位验证码'}
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} ${'获取验证码'}`;
                  }
                  return '获取验证码';
                }}
                name="vcode"
                rules={[
                  {
                    required: true,
                    message: '请输入6位验证码',
                    min: 6,
                    max: 6
                  },
                ]}
                onGetCaptcha={async () => {
                  if(!MOBILE_REGEXP.test(mobile)){
                    message.warning('请输入正确格式的手机号后获取验证码');
                    return Promise.reject();
                  }

                  const cacheVcodeKey = loginVcodeKeyStorage.get(mobile);

                  const res = await vcodeV1ControllerSendMobileVcode({
                    mobile,
                    vcodeKey: cacheVcodeKey ?? undefined,
                    type: SendVcodeType.USER_LOGIN,
                  })

                  if(res.vcodeKey === cacheVcodeKey){
                    message.success('您的上次验证码还未失效，请直接使用');
                    return Promise.reject();
                  }else{
                    loginVcodeKeyStorage.set(mobile, res.vcodeKey);
                    message.success('获取验证码成功！');
                  }
                }}
              />
            }
          }
        </ProFormDependency>
      </>
    )}
    {loginType === 'mobilePassword' && (
      <>
        <ProFormText.Password
          name="password"
          fieldProps={{
            size: 'large',
            prefix: <LockOutlined />,
          }}
          placeholder="密码"
          rules={[
            {
              required: true,
              message: '请输入密码',
            },
          ]}
        />
      </>
    )}
    <div
      style={{
        marginBottom: 24,
      }}
      className="flex justify-between"
    >
      <a onClick={()=>{
        openRegisterModal();
      }}>还没有账号？立即注册</a>
      <a>
        忘记密码
      </a>
    </div>
  </LoginForm>
}

let modal: ReturnType<typeof Modal.info> | null = null;

export const openLoginModal = ()=>{
  if(modal){
    return modal;
  }
  modal = Modal.info({
    title: null,
    icon: null,
    width: 600,
    footer: null,
    closable: true,
    content: <Login onSuccess={()=>{
      modal?.destroy();
      modal = null;
    }} />,
    onCancel: ()=>{
      modal?.destroy();
      modal = null;
    }
  })
  return modal;
}

type LoginType = 'mobileVcode' | 'mobilePassword';
